<template>
  <base-table-layout
    title="供应商管理"
    :total="total"
    :current-page="currentPage"
    :page-size="pageSize"
    @update:currentPage="val => currentPage = val"
    @update:pageSize="val => pageSize = val"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  >
    <!-- 搜索区域 -->
    <template #search>
      <el-input
        v-model="searchForm.supplierName"
        placeholder="供应商名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleSearch"
      />
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleSearch"
      >搜索</el-button>
      <el-button
        class="filter-item"
        type="info"
        icon="el-icon-refresh"
        @click="resetSearch"
      >重置</el-button>
    </template>

    <!-- 操作区域 -->
    <template #operation>
      <el-button
        type="success"
        icon="el-icon-plus"
        @click="handleAdd"
      >新增</el-button>
      <!-- 新增批量删除按钮 -->
      <el-button
        type="danger"
        icon="el-icon-delete"
        @click="handleBatchDelete"
      >批量删除</el-button>
    </template>

    <!-- 表格区域 -->
    <template #table>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="56"
        />
        <el-table-column prop="supplierName" label="供应商名称" width="320" />
        <el-table-column prop="contactPerson" label="负责人" />
        <el-table-column prop="contactPhone" label="联系电话" />
        <el-table-column prop="address" label="地址" width="350"/>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!-- 弹窗区域 -->
    <template #dialogs>
      <!-- 新增/编辑供应商对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
        <el-form :model="supplierForm" :rules="rules" ref="supplierForm" label-width="100px">
          <el-form-item label="供应商名称" prop="supplierName">
            <el-input v-model="supplierForm.supplierName"></el-input>
          </el-form-item>
          <el-form-item label="联系人" prop="contactPerson">
            <el-input v-model="supplierForm.contactPerson"></el-input>
          </el-form-item>
          <el-form-item label="联系电话" prop="contactPhone">
            <el-input v-model="supplierForm.contactPhone"></el-input>
          </el-form-item>
          <el-form-item label="地址" prop="address">
            <el-input v-model="supplierForm.address"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-dialog>
    </template>
  </base-table-layout>
</template>

<script>
import request from '@/utils/request'
import _ from 'lodash'
import BaseTableLayout from '@/components/BaseTableLayout.vue'

export default {
  name: 'SupplierPage',
  components: {
    BaseTableLayout
  },
  data() {
    return {
      loading: false,
      searchForm: {
        supplierName: ''
      },
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: '',
      supplierForm: {
        supplierName: '',
        contactPerson: '',
        contactPhone: '',
        address: ''
      },
      rules: {
        supplierName: [
          { required: true, message: '请输入供应商名称', trigger: 'blur' }
        ],
        contactPerson: [
          { required: true, message: '请输入联系人', trigger: 'change' }
        ],
        contactPhone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' }
        ],
        address: [
          { required: false, message: '请输入地址', trigger: 'blur' }
        ]
      },
      selectedRows: [] // 新增选中的行
    }
  },
  methods: {
    async handleLoadData() {
      try {
        const response = await request.get('/supplier/page', {
          params: {
            page: this.currentPage,
            size: this.pageSize,
            supplierName: this.searchForm.supplierName || undefined
          }
        })
        
        this.tableData = response.records;
        this.total = response.total;
      } catch (error) {
        this.$message.error(error || '获取供应商数据失败')
        this.tableData = []
        this.total = 0
      }
    },

    handleSearch: _.debounce(async function () {
      this.currentPage = 1
      await this.handleLoadData()
    }, 300),

    async resetSearch() {
      this.searchForm.supplierName = ''
      this.currentPage = 1
      await this.handleLoadData()
    },

    handleAdd() {
      this.dialogTitle = '新增供应商'
      this.supplierForm = {
        supplierName: '',
        contactPerson: '',
        contactPhone: '',
        address: ''
      }
      this.dialogVisible = true
    },

    handleEdit(row) {
      this.dialogTitle = '编辑供应商'
      this.supplierForm = {
        ...row,
        supplierId: row.supplierId
      }
      this.dialogVisible = true
    },

    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该供应商信息吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        await request.delete(`/supplier/${row.supplierId}`)

        this.$message.success('删除成功')
        await this.handleLoadData()
      } catch (error) {
        if (error === 'cancel') {
          this.$message.info('已取消删除')
        } else {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      }
    },

    // 新增选择行的方法
    handleSelectionChange(val) {
      this.selectedRows = val
    },

    async handleBatchDelete() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请选择要删除的供应商')
        return
      }

      try {
        await this.$confirm('确认删除选中的供应商吗？', '提示', {
          type: 'warning'
        })

        const supplierIds = this.selectedRows.map(row => row.supplierId)
        await request.delete('/supplier/batch', {
          data: supplierIds
        })

        this.$message.success('批量删除成功')
        await this.handleLoadData()
      } catch (error) {
        if (error === 'cancel') {
          this.$message.info('已取消删除')
        } else {
          console.error('批量删除失败:', error)
          this.$message.error('批量删除失败')
        }
      }
    },

    async handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      await this.handleLoadData()
    },

    async handleCurrentChange(val) {
      this.currentPage = val
      await this.handleLoadData()
    },

    async submitForm() {
      try {
        const valid = await this.$refs.supplierForm.validate()
        if (!valid) return

        const formData = {
          ...this.supplierForm
        }

        if (this.supplierForm.supplierId) {
          formData.supplierId = this.supplierForm.supplierId
          await request.put('/supplier', formData)
        } else {
          await request.post('/supplier', formData)
        }

        this.$message.success(this.supplierForm.supplierId ? '更新成功' : '添加成功')
        this.dialogVisible = false
        await this.handleLoadData()
      } catch (error) {
        console.error('保存失败:', error)
        this.$message.error('保存失败，请稍后重试')
      }
    }
  },
  created() {
    this.handleLoadData()
  }
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.operation-bar {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.el-button {
  margin-left: 10px;
}

.el-table {
  margin-top: 20px;
}

.el-table th,
.el-table td {
  padding: 12px 0;
}

.el-table th {
  background-color: #f5f7fa;
  color: #909399;
}

.el-table .el-button {
  padding: 7px 15px;
  font-size: 12px;
}

.el-table .el-button + .el-button {
  margin-left: 5px;
}
</style>